//
//  XFOauthViewController.swift
//  SinaBlog
//
//  Created by macs on 15/11/9.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OauthViewController: UIViewController {
    
    
    let webView = UIWebView()
    
    @objc func fullDidClick (){
        //469770143@qq.com    17v77.com   15515064587 gxf5211314
        //执行一段js代码,添加账号,密码
        let jsStr = "document.getElementById('userId').value = '15515064587',document.getElementById('passwd').value = 'gxf5211314';"
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
    
    @objc func backDidClick () {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        webView.backgroundColor = UIColor.redColor()
        setupUI()
        
        loadOauthPage()
    }
    
    override func viewWillDisappear(animated: Bool) {
        //注册界面即将消失
        SVProgressHUD.dismiss()
    }
    
    func loadOauthPage(){
        //加载登陆界面
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    
    func setupUI(){
        //添加NAVgationItem的左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: . Plain, target: self, action: "backDidClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动补充", style: .Plain, target: self, action: "fullDidClick")
        
    }
    
}

extension OauthViewController : UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        //
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //在這裡可以监控到所有网络跳转 url
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
//        print(urlString)
        //查看是否跳转微博登陆及授权界面
        if urlString.hasPrefix("https://api.weibo"){
            return true
        }
        //查看是否跳转到回调界面
        if !urlString.hasPrefix(redirect_uri){
            return false
        }
        //这里一定是走过了回调页面的
//        print(request.URL?.query)
        guard let query = request.URL?.query else {
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        AccessViewModel().getAccess_token(code) { (error) -> () in
            //回调参数
            if error == nil {
                SVProgressHUD.showInfoWithStatus("登录成功")
                //在4.0以前, dismiss 操作是有调用present得viewController在代理方法中来调用的
                //通知是同步执行的,放到闭包里确定回到登陆界面之后,释放了网页界面,然后在进行切换到欢迎界面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(notityKey, object: "welcome", userInfo: nil)
                    return
                })
            }
            print(error)
            SVProgressHUD.showErrorWithStatus(NetErrorTip)
        }
        //这样就不会跳转到回调页面
        return false
    }
    
    
}
